package com.lushuan.ch11_springboot_test.demo.threadpool;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo1 {


    static  Integer num=0;

    public static void main(String[] args) {

//        casDemo1();
        casDemo2();
        casDemo3();


    }

    // 无锁演示
    public static void casDemo1() {
        // 循环启动三条线程，打印计数信息
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 无锁的一种状态
                    while (num < 1000) {
                        System.out.println("Thread"+Thread.currentThread().getName()+"-"+num++);
                    }

                }
            });
            thread.start();
        }
    }

    // 有锁演示，悲观锁
    public static void casDemo2() {
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 使用互斥锁，悲观锁，会按照顺序进行输出
                    synchronized (CASDemo1.class) {
                        while (num < 1000) {
                            System.out.println("Thread"+Thread.currentThread().getName()+"-"+num++);
                        }
                    }
                }
            });
            thread.start();
        }
    }


    static AtomicInteger atomicNum = new AtomicInteger(0);
    // 无锁演示，乐观锁
    public static void casDemo3() {
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (atomicNum.get() < 1000) {
                        System.out.println("Thread"+Thread.currentThread().getName()+"-"+atomicNum.incrementAndGet());
                    }
                }
            });
            thread.start();
        }
    }




}
